package filter;

import servlet.SelectShopCarServlet;
import user.ShopCar;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//拦截提交空购物车导致结算异常
public class OrderconFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        if(request.getSession().getAttribute("shopCar")==null){
            response.getWriter().println("请先登录！！！（2秒后自动跳转）");
            response.setHeader("refresh", "2;URL=login.jsp");
            return;
        }

        SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
        selectShopCarServlet.doGet(request, response); //从数据库读取购物车

        List<ShopCar> shopCar= (List<ShopCar>) session.getAttribute("shopCar");

        if (shopCar!=null&&shopCar.size()>0){
            chain.doFilter(request, response);
        }else {
            response.getWriter().println("请先添加商品！！！（2秒后自动跳转）");
            response.setHeader("refresh","2;URL=shop.jsp");
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
